package com.blindnews.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
@Slf4j
@Component
public class VolumeAdjust {
    public void volumeAd(String type){
        try {
            if (type == null || "".equals(type.trim())) {
                log.info("type 参数为空,不进行操作...");
            }
            /**tempFile：vbs 文件
             * vbsMessage：vbs 文件的内容*/
            String vbsMessage;
            File tempFile;
            Runtime runtime = Runtime.getRuntime();
            switch (type) {
//                静音或取消静音
                case "0":
                    tempFile = new File("temp", "volumeMute.vbs");
                    vbsMessage = !tempFile.exists() ? "CreateObject(\"Wscript.Shell\").Sendkeys \"棴\"" : "";
                    break;
//                    调高音量+2
                case "1":
                    tempFile = new File("temp", "volumeAdd.vbs");
                    vbsMessage = !tempFile.exists() ? "for i=1 to 5\n" +
                            "CreateObject(\"Wscript.Shell\").Sendkeys \"棷\"\n" +
                            "next" : "";
                    break;
//                    调小音量-2
                case "2":
                    tempFile = new File("temp", "volumeMinus.vbs");
                    vbsMessage = !tempFile.exists() ? "for i=1 to 5\n" +
                            "CreateObject(\"Wscript.Shell\").Sendkeys \"棶\"\n" +
                            "next" : "";
                    break;
                default:
                    return;
            }
            /**
             * 当3个vbs文件不存在时，则创建它们，应用默认编码为 utf-8 时，创建的 vbs 脚本运行时报错
             * 于是使用 OutputStreamWriter 将 vbs 文件编码改成gbd就正常了
             */
            if (!tempFile.exists() && !vbsMessage.equals("")) {
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdirs();
                }
                tempFile.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "GBK");
                outputStreamWriter.write(vbsMessage);
                outputStreamWriter.flush();
                outputStreamWriter.close();
                log.info("vbs 文件不存在，新建成功：" + tempFile.getAbsolutePath());
            }

            runtime.exec("wscript " + tempFile.getAbsolutePath()).waitFor();

            log.info("音量控制完成.");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
